﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Singer.Shared;
using Singer.Core;

namespace Singer.Framework.CoreFilters
{
    /// <summary>
    /// WebApi 接口返回结果统一处理过滤器
    /// </summary>
    public class CoreApiResultFilter : IAsyncResultFilter
    {
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (typeof(Controller).IsAssignableFrom(context.Controller.GetType()))//不处理MVC控制器
            {
                await next.Invoke();
                return;
            }
            if (context.Result is EmptyResult)
            {
                context.Result = new ObjectResult(CoreApiResult.Success());
            }
            if (context.Result is ObjectResult _o)
            {
                if (_o.Value is not CoreApiResult) 
                    context.Result = new ObjectResult(CoreApiResult.Success(_o.Value));
            }
            var objectresult = context.Result as ObjectResult;
            var cotentresult = new ContentResult()
            {
                Content = JsonUtils.ToJson(objectresult?.Value ?? ""),
                ContentType = "application/json",
                StatusCode = 200
            };
            context.Result = cotentresult;
            await next.Invoke();
        }
    }
}
